package com.study.handler;

import com.alibaba.fastjson.JSONObject;
import com.study.enums.ResultCodeEnum;
import com.study.exception.MyException;
import com.study.pojo.common.Result;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 异常捕获类
 * ControllerAdvice被@Component标记，所以他可以被组件扫描到并放入Spring容器
 */

@RestControllerAdvice(basePackages = "com.study.controller")
public class ExceptionHandler {
    /**
     * 方法参数无效异常
     */
    @org.springframework.web.bind.annotation.ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<?> PMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String defaultMessage = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();

        return Result.failed(ResultCodeEnum.VALIDATE_ERROR, defaultMessage);
    }

    /**
     * 请求方式不支持
     */
    @org.springframework.web.bind.annotation.ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Result<?> PHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {

        return Result.failed("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * MyException 错误 我自己定义的
     */
    @org.springframework.web.bind.annotation.ExceptionHandler({MyException.class})
    public Result<?> PMyException(MyException e) {
        System.out.println("MyException => " + e.getMessage() + " => " + e.getCodeEnum());

        if (e.getMessage() == null)
            return Result.failed(e.getCodeEnum());

        return Result.failed(e.getCodeEnum(), e.getMessage());
    }


    /**
     * 顶级异常捕获并统一处理，当其他异常无法处理时候选择使用
     */
    @org.springframework.web.bind.annotation.ExceptionHandler({Exception.class})
    public Result<?> PException(Exception ex) {
        System.out.println(ex.getMessage() + "=> " + ex.getClass());
        return Result.failed(ex.getMessage());
    }


}
